import React, { useState,useEffect } from 'react';
import { Form, Input, Select, Switch, Button, Space, Card, Typography, Tag, InputNumber } from 'antd';
import { PlusOutlined, MinusCircleOutlined } from '@ant-design/icons';
import { Prompt, PromptFormValues, PromptType, PromptStatus, VariableType, Variable } from './store/promptTypes';

const { TextArea } = Input;
const { Title } = Typography;

interface PromptFormProps {
  initialValues?: Prompt;
  type?: 'create' | 'edit' | 'view';
  onSubmit: (values: PromptFormValues) => void;
  onCancel: () => void;
}

const PromptForm: React.FC<PromptFormProps> = ({ initialValues, type, onSubmit, onCancel }) => {
  const [form] = Form.useForm();
  useEffect(() => {
    form.resetFields();
    if (initialValues) {
      form.setFieldsValue(initialValues);
    }
  }, [initialValues, form]);

  const [variablesArray, setVariables] = useState<Variable[]>(initialValues?.variablesArray || []);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      onSubmit({ ...values, variablesArray });
    } catch (error) {
      console.error('表单验证失败:', error);
    }
  };

  const handleAddVariable = () => {
    setVariables([...variablesArray, {
      name: '',
      type: VariableType.STRING,
      required: false,
    }]);
  };

  const handleRemoveVariable = (index: number) => {
    const newVariables = [...variablesArray];
    newVariables.splice(index, 1);
    setVariables(newVariables);
  };

  const handleVariableChange = (index: number, field: keyof Variable, value: any) => {
    const newVariables = [...variablesArray];
    newVariables[index] = { ...newVariables[index], [field]: value };
    setVariables(newVariables);
  };
  const isViewMode = type === 'view';

  return (
    <Form
      form={form}
      layout="vertical"
      initialValues={initialValues}
      disabled={isViewMode}
      onFinish={handleSubmit}
    >
      {/* 基本信息卡片 */}
      <Card title="基本信息" style={{ marginBottom: 16 }}>
        <Form.Item
          name="name"
          label="提示词名称"
          rules={[
            { required: true, message: '请输入提示词名称' },
            { max: 50, message: '提示词名称不能超过50个字符' }
          ]}
        >
          <Input placeholder="请输入提示词名称" />
        </Form.Item>

        <Form.Item
          name="identifier"
          label="提示词标识"
          rules={[
            { required: true, message: '请输入提示词标识' },
            { pattern: /^[a-zA-Z0-9_]+$/, message: '只能输入英文、数字和下划线' },
            { max: 30, message: '提示词标识不能超过30个字符' }
          ]}
        >
          <Input placeholder="请输入提示词标识" />
        </Form.Item>

        <Form.Item
          name="type"
          label="提示词类型"
          rules={[{ required: true, message: '请选择提示词类型' }]}
        >
          <Select placeholder="请选择提示词类型">
            {Object.values(PromptType).map(type => (
              <Select.Option key={type} value={type}>
                {type}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item
          name="backgroundPrompt"
          label="背景提示词"
          rules={[
            { max: 2000, message: '背景提示词不能超过2000个字符' }
          ]}
        >
          <TextArea rows={4} placeholder="请输入背景提示词，用于设置模型的背景知识和行为规范" />
        </Form.Item>

        <Form.Item
          name="content"
          label="提示词模板"
          rules={[
            { required: true, message: '请输入提示词模板' },
            { max: 5000, message: '提示词模板不能超过5000个字符' }
          ]}
        >
          <TextArea rows={6} placeholder="请输入提示词模板，可以使用 {变量名} 的形式插入变量" />
        </Form.Item>

        <Form.Item
          name="description"
          label="提示词描述"
          rules={[{ max: 500, message: '描述不能超过500个字符' }]}
        >
          <TextArea rows={4} placeholder="请输入提示词描述" />
        </Form.Item>

        <Form.Item
          name="version"
          label="版本号"
          rules={[
            { required: true, message: '请输入版本号' },
            { pattern: /^[0-9]+\.[0-9]+\.[0-9]+$/, message: '版本号格式不正确，如：1.0.0' }
          ]}
        >
          <Input placeholder="请输入版本号" />
        </Form.Item>

        <Form.Item
          name="status"
          label="状态"
          rules={[{ required: true, message: '请选择状态' }]}
        >
          <Select placeholder="请选择状态">
            {Object.values(PromptStatus).map(status => (
              <Select.Option key={status} value={status}>
                {status}
              </Select.Option>
            ))}
          </Select>
        </Form.Item>
      </Card>

      {/* 变量设置卡片 */}
      <Card title="变量设置" style={{ marginBottom: 16 }}>
        {Array.from(variablesArray)?.map((variable, index) => (
          <div key={index} style={{ marginBottom: 16, padding: 16, border: '1px solid #d9d9d9', borderRadius: 4 }}>
            <Space align="baseline">
              <Form.Item
                label="变量名"
                required
                style={{ marginBottom: 0 }}
              >
                <Input
                  value={variable.name}
                  onChange={e => handleVariableChange(index, 'name', e.target.value)}
                  placeholder="请输入变量名"
                />
              </Form.Item>
              <Form.Item
                label="类型"
                required
                style={{ marginBottom: 0 }}
              >
                <Select
                  value={variable.type}
                  onChange={value => handleVariableChange(index, 'type', value)}
                  style={{ width: 120 }}
                >
                  {Object.values(VariableType).map(type => (
                    <Select.Option key={type} value={type}>
                      {type}
                    </Select.Option>
                  ))}
                </Select>
              </Form.Item>
              <Form.Item
                label="是否必填"
                style={{ marginBottom: 0 }}
              >
                <Switch
                  checked={variable.required}
                  onChange={checked => handleVariableChange(index, 'required', checked)}
                />
              </Form.Item>
              <Button
                type="text"
                danger
                icon={<MinusCircleOutlined />}
                onClick={() => handleRemoveVariable(index)}
              />
            </Space>
            <Form.Item
              label="描述"
              style={{ marginBottom: 0 }}
            >
              <Input
                value={variable.description}
                onChange={e => handleVariableChange(index, 'description', e.target.value)}
                placeholder="请输入变量描述"
              />
            </Form.Item>
            <Form.Item
              label="默认值"
              style={{ marginBottom: 0 }}
            >
              <Input
                value={variable.defaultValue}
                onChange={e => handleVariableChange(index, 'defaultValue', e.target.value)}
                placeholder="请输入默认值"
              />
            </Form.Item>
          </div>
        ))}
        <Button type="dashed" onClick={handleAddVariable} block icon={<PlusOutlined />}>
          添加变量
        </Button>
      </Card>

      {/* 高级设置卡片 */}
      <Card title="高级设置" style={{ marginBottom: 16 }}>
        <Form.Item
          name="tags"
          label="标签"
        >
          <Select
            mode="tags"
            style={{ width: '100%' }}
            placeholder="请输入标签"
          />
        </Form.Item>

        <Form.Item
          name="modelIds"
          label="适用的模型"
        >
          <Select
            mode="multiple"
            style={{ width: '100%' }}
            placeholder="请选择适用的模型"
          />
        </Form.Item>

        <Form.Item
          name="isPublic"
          label="是否公开"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>

        <Form.Item
          name="isTemplate"
          label="是否模板"
          valuePropName="checked"
        >
          <Switch />
        </Form.Item>
      </Card>

      {/* 表单按钮 */}
      <Form.Item>
        <Space>
          <Button type="primary" htmlType="submit">
            保存
          </Button>
          <Button onClick={onCancel}>
            取消
          </Button>
        </Space>
      </Form.Item>
    </Form>
  );
};

export default PromptForm;